import { createRouter, createWebHashHistory } from 'vue-router'
import Home from '../views/Home.vue'
import Login from '../views/Login.vue'
import Register from '../views/Register.vue'
import GocJudgePage from '../views/GocJudgePage.vue'
import { beforePageNavigation } from '../utils/editor-cleanup.js'
import logger from '../utils/logger.js'

// 定义路由
const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home,
    meta: { title: '代码小英雄 - 助力孩子编程成长' }
  },
  {
    path: '/problems',
    name: 'Problems',
    component: () => import(/* webpackChunkName: "problems" */ '../views/Problems.vue'),
    meta: { title: '题目列表 - 代码小英雄' }
  },
  {
    path: '/problem/:id',
    name: 'ProblemDetail',
    component: () => import(/* webpackChunkName: "problem-detail" */ '../views/ProblemDetail.vue')
  },
  {
    path: '/question/create',
    name: 'QuestionCreate',
    component: () => import(/* webpackChunkName: "question-create" */ '../views/QuestionCreate.vue')
  },
  {
    path: '/question/edit/:id',
    name: 'QuestionEdit',
    component: () => import(/* webpackChunkName: "question-edit" */ '../views/QuestionEdit.vue')
  },
  {
    path: '/my-questions',
    name: 'MyQuestions',
    component: () => import(/* webpackChunkName: "my-questions" */ '../views/MyQuestions.vue')
  },
  {
    path: '/shared-questions',
    name: 'SharedQuestions',
    component: () => import(/* webpackChunkName: "shared-questions" */ '../views/SharedQuestions.vue')
  },
  {
    path: '/received-questions',
    name: 'ReceivedQuestions',
    component: () => import(/* webpackChunkName: "received-questions" */ '../views/ReceivedQuestions.vue')
  },
  {
    path: '/assign-homework',
    name: 'AssignHomework',
    component: () => import(/* webpackChunkName: "assign-homework" */ '../views/AssignHomework.vue')
  },
  {
    path: '/homework/create',
    name: 'HomeworkCreate',
    component: () => import(/* webpackChunkName: "homework-create" */ '../views/HomeworkCreate.vue')
  },
  {
    path: '/homework/edit/:id',
    name: 'HomeworkEdit',
    component: () => import(/* webpackChunkName: "homework-edit" */ '../views/HomeworkEdit.vue')
  },
  {
    path: '/homework-detail',
    name: 'HomeworkDetail',
    component: () => import(/* webpackChunkName: "homework-detail" */ '../views/HomeworkDetail.vue'),
    meta: { title: '作业详情 - 代码小英雄' }
  },
  {
    path: '/teacher-homework-view/:id',
    name: 'TeacherHomeworkView',
    component: () => import(/* webpackChunkName: "teacher-homework-view" */ '../views/TeacherHomeworkView.vue'),
    meta: { title: '查看作业详情 - 代码小英雄' }
  },
  {
    path: '/student-ranking',
    name: 'StudentRanking',
    component: () => import(/* webpackChunkName: "student-ranking" */ '../views/StudentRanking.vue')
  },
  {
    path: '/login',
    name: 'Login',
    component: Login
  },
  {
    path: '/register',
    name: 'Register',
    component: Register
  },
  {
    path: '/news',
    name: 'News',
    component: () => import(/* webpackChunkName: "news" */ '../views/News.vue')
  },
  {
    path: '/news/detail/:id',
    name: 'NewsDetail',
    component: () => import(/* webpackChunkName: "news-detail" */ '../views/NewsDetail.vue')
  },
  {
    path: '/news/create',
    name: 'NewsCreate',
    component: () => import(/* webpackChunkName: "news-create" */ '../views/NewsCreate.vue')
  },
  {
    path: '/test',
    name: 'Test',
    component: () => import(/* webpackChunkName: "test" */ '../views/Test.vue')
  },
  {
    path: '/personal-center',
    name: 'PersonalCenter',
    component: () => import(/* webpackChunkName: "profile" */ '../views/Profile.vue')
  },
  {
    path: '/profile',
    name: 'Profile',
    component: () => import(/* webpackChunkName: "profile" */ '../views/Profile.vue')
  },
  {
    path: '/progress',
    name: 'Progress',
    component: () => import(/* webpackChunkName: "progress" */ '../views/Profile.vue')
  },
  {
    path: '/work',
    name: 'Work',
    component: () => import(/* webpackChunkName: "work" */ '../views/Profile.vue')
  },
  {
    path: '/student-work',
    name: 'StudentWork',
    component: () => import(/* webpackChunkName: "student-work" */ '../views/Profile.vue')
  },
  {
    path: '/documents',
    name: 'Documents',
    component: () => import(/* webpackChunkName: "documents" */ '../views/Profile.vue')
  },
  {
    path: '/management',
    name: 'Management',
    component: () => import(/* webpackChunkName: "management" */ '../views/Management.vue')
  },
  {
    path: '/goc-judge',
    name: 'GocJudge',
    component: GocJudgePage
  },
  {
    path: '/goc-editor',
    name: 'GocEditor',
    component: () => import(/* webpackChunkName: "goc-editor" */ '../views/GocEditorPage.vue')
  },
  {
    path: '/test-integration',
    name: 'TestIntegration',
    component: () => import(/* webpackChunkName: "test-integration" */ '../views/TestIntegration.vue')
  },
  {
    path: '/navigation-test',
    name: 'NavigationTest',
    component: () => import(/* webpackChunkName: "navigation-test" */ '../views/NavigationTest.vue')
  },
  {
    path: '/my-team',
    name: 'MyTeam',
    component: () => import(/* webpackChunkName: "my-team" */ '../views/MyTeam.vue'),
    meta: { title: '我的团队 - 代码小英雄' }
  },
  {
    path: '/add-students',
    name: 'AddStudents',
    component: () => import(/* webpackChunkName: "add-students" */ '../views/AddStudents.vue'),
    meta: { title: '添加学生账号 - 代码小英雄' }
  },
  {
    path: '/add-teacher',
    name: 'AddTeacher',
    component: () => import(/* webpackChunkName: "add-teacher" */ '../views/AddTeacher.vue'),
    meta: { title: '管理员添加教师 - 代码小英雄' }
  },
  {
    path: '/contest-management',
    name: 'ContestManagement',
    component: () => import(/* webpackChunkName: "contest-management" */ '../views/ContestManagement.vue'),
    meta: { title: '比赛管理 - 代码小英雄' }
  },
  {
    path: '/contest-create',
    name: 'ContestCreate',
    component: () => import(/* webpackChunkName: "contest-create" */ '../views/ContestCreate.vue'),
    meta: { title: '创建比赛 - 代码小英雄' }
  },
  {
    path: '/contest-edit/:id',
    name: 'ContestEdit',
    component: () => import(/* webpackChunkName: "contest-edit" */ '../views/ContestEdit.vue'),
    meta: { title: '编辑比赛 - 代码小英雄' }
  },
  {
    path: '/contest-detail/:id',
    name: 'ContestDetail',
    component: () => import(/* webpackChunkName: "contest-detail" */ '../views/ContestDetail.vue'),
    meta: { title: '比赛详情 - 代码小英雄' }
  },
  {
    path: '/contests',
    name: 'Contests',
    component: () => import(/* webpackChunkName: "contests" */ '../views/Contests.vue'),
    meta: { title: '比赛列表 - 代码小英雄' }
  },
  {
    path: '/contest-exam/:id',
    name: 'ContestExam',
    component: () => import(/* webpackChunkName: "contest-exam" */ '../views/ContestExam.vue'),
    meta: { title: '比赛答题 - 代码小英雄' }
  }

]

// 创建路由实例
const router = createRouter({
  history: createWebHashHistory(),
  routes
})

// 路由守卫 - JWT令牌访问权限验证
router.beforeEach((to, from, next) => {
  logger.log(`🛣️ 路由跳转: 从 ${from.path} 到 ${to.path}`);
  
  // 防止无限重定向的保护机制
  if (to.path === from.path) {
    logger.log('⚠️ 检测到相同路径跳转，跳过路由守卫');
    next();
    return;
  }
  
  // 特殊处理：从编辑器页面跳转时强制清理资源
  if (from.path === '/goc-editor' || from.path === '/goc-judge' || from.path.startsWith('/problem/')) {
    logger.log('🧹 [路由守卫] 从编辑器相关页面跳转，执行强制清理');
    try {
      beforePageNavigation();
    } catch (error) {
      logger.warn('⚠️ [路由守卫] 清理编辑器资源时出错:', error);
    }
  }
  
  // 获取JWT令牌
  const token = localStorage.getItem('token');
  const hasToken = !!token;
  
  logger.log('🔍 JWT令牌状态:', hasToken ? '已登录' : '未登录');
  
  // 定义公开页面（无需登录即可访问）
  const publicPages = ['/', '/login', '/register', '/news', '/goc-editor', '/test-integration', '/navigation-test'];
  const isPublicPage = publicPages.includes(to.path) || to.path.startsWith('/news/');
  
  logger.log('📖 页面类型:', isPublicPage ? '公开页面' : '需要登录的页面');
  
  // 访问权限逻辑:
  // 1. 有令牌的用户可以访问所有页面（包括首页、登录、注册页）
  // 2. 没有令牌的用户只能访问公开页面（首页、登录、注册页）
  if (!hasToken && !isPublicPage) {
    logger.log('❌ 无JWT令牌，重定向到登录页');
    // 防止无限重定向：如果已经在登录页，直接放行
    if (to.path === '/login') {
      logger.log('⚠️ 已在登录页，直接放行');
      next();
      return;
    }
    next('/login');
    return;
  }
  
  logger.log('✅ 访问权限验证通过');
  logger.log('🔧 当前路由配置:', to);
  
  next();
})

// 添加导航失败处理
router.onError((error) => {
  logger.error('路由导航出错:', error);
  
  // 如果是组件加载失败，尝试重新加载页面
  if (error.message && error.message.includes('Loading chunk')) {
    logger.warn('检测到组件加载失败，尝试重新加载页面');
    window.location.reload();
  }
  
  // 如果是网络错误，提供用户友好的提示
  if (error.message && error.message.includes('network')) {
    logger.warn('检测到网络问题，建议用户检查网络连接');
    // 可以在这里添加用户提示
  }
})

// 设置页面标题
router.beforeEach((to, from, next) => {
  // 设置页面标题
  if (to.meta && to.meta.title) {
    document.title = to.meta.title
  } else {
    document.title = '代码小英雄 - 青少年编程教育平台'
  }
  next()
})

export default router 